package com.liao.rabbitmq.confirm;

import com.liao.rabbitmq.utils.RabbitConstant;
import com.liao.rabbitmq.utils.RabbitUtils;
import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 发布者
 */
public class Producer {

    public static void main(String[] args) throws Exception {
        Map area = new LinkedHashMap<String, String>();
        area.put("routing.one.a.20201127", "中国湖南长沙20201127私密数据");
        area.put("routing.one.d.20201128", "中国河北石家庄20201128私密数据");
        area.put("routing.two.b.20201127", "中国湖北武汉20201127私密数据");
        area.put("routing.two.e.20201128", "中国湖北武汉20201128私密数据");
        area.put("routing.three.c.20201127", "中国湖南株洲20201127私密数据");
        area.put("routing.three.f.20201128", "中国河南郑州20201128私密数据");
        area.put("us.one.a.20201127", "美国加州洛杉矶20201127私密数据");
        area.put("us.two.b.20201128", "美国加州洛杉矶20201128私密数据");
        Connection connection = RabbitUtils.getConnection();
        Channel channel = connection.createChannel();
        //开启confirm监听模式
        channel.confirmSelect();
        channel.addConfirmListener(new ConfirmListener() {
            public void handleAck(long l, boolean b) throws IOException {
                //第二个参数代表接收的数据是否为批量接收，一般我们用不到。
                System.out.println("消息已被Broker接收,Tag:" + l );
            }

            public void handleNack(long l, boolean b) throws IOException {
                System.out.println("消息已被Broker拒收,Tag:" + l);
            }
        });
        channel.addReturnListener(new ReturnCallback() {
            public void handle(Return r) {
                System.err.println("===========================");
                System.err.println("Return编码：" + r.getReplyCode() + "-Return描述:" + r.getReplyText());
                System.err.println("交换机:" + r.getExchange() + "-路由key:" + r.getRoutingKey() );
                System.err.println("Return主题：" + new String(r.getBody()));
                System.err.println("===========================");
            }
        });
        Iterator<Map.Entry<String, String>> itr = area.entrySet().iterator();
        while (itr.hasNext()) {
            Map.Entry<String, String> me = itr.next();
            //第一个参数交换机名字   第二个参数作为 消息的routing key
            channel.basicPublish(RabbitConstant.EXCHANGE_CONTENT_TOPIC,me.getKey() , null , me.getValue().getBytes());
        }
        //如果关闭则无法进行监听，因此此处不需要关闭
        /*channel.close();
        connection.close();*/

        Thread.sleep(5000);
    }
}
